<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="作业名称" prop="jobName">
                <el-input v-model="queryParams.jobName" placeholder="请输入作业名称" clearable style="width: 240px" />
            </el-form-item>
            <el-form-item label="执行结果" prop="success">
                <el-select v-model="queryParams.success" placeholder="请选择结果" clearable style="width: 240px">
                    <el-option v-for="item in sys_result" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
                <el-button icon="refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="danger" plain icon="delete" :disabled="multiple" @click="handleDelete"
                    v-hasFunc="'job:log:del'">删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="delete" @click="handleClearAll" v-hasFunc="'job:log:clear'">
                    一键清空
                </el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" ref="tableRef" :data="dataList" @selection-change="handleSelectionChange"
            highlight-current-row @row-click="handleRowClick">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="主键" align="center" prop="historyId" :show-overflow-tooltip="true"
                v-if="columns.showColumn('historyId')">
                <template #default="scope">
                    {{ scope.row.historyId }}
                </template>
            </el-table-column>
            <el-table-column label="作业标识" align="center" prop="jobId" :show-overflow-tooltip="true"
                v-if="columns.showColumn('jobId')">
                <template #default="scope">
                    {{ scope.row.jobId }}
                </template>
            </el-table-column>
            <el-table-column label="作业名" align="center" prop="jobName" :show-overflow-tooltip="true"
                v-if="columns.showColumn('jobName')">
                <template #default="{ row }">
                    {{ row.job?.name }}
                </template>
            </el-table-column>
            <el-table-column label="触发编码" align="center" prop="triggerId" :show-overflow-tooltip="true"
                v-if="columns.showColumn('triggerId')">
                <template #default="scope">
                    {{ scope.row.triggerId }}
                </template>
            </el-table-column>
            <el-table-column label="执行编码" align="center" prop="fireInstanceId" :show-overflow-tooltip="true"
                v-if="columns.showColumn('fireInstanceId')">
                <template #default="scope">
                    {{ scope.row.fireInstanceId }}
                </template>
            </el-table-column>
            <el-table-column label="执行时间" align="center" prop="startTime" :show-overflow-tooltip="true"
                v-if="columns.showColumn('startTime')">
                <template #default="{ row }">
                    {{ parseTime(row.startTime) }}
                </template>
            </el-table-column>
            <el-table-column label="结束时间" align="center" prop="endTime" :show-overflow-tooltip="true"
                v-if="columns.showColumn('endTime')">
                <template #default="{ row }">
                    {{ parseTime(row.endTime) }}
                </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createdAt" :show-overflow-tooltip="true"
                v-if="columns.showColumn('createdAt')">
                <template #default="{ row }">
                    {{ parseTime(row.createdAt) }}
                </template>
            </el-table-column>
            <el-table-column label="作业结果" align="center" prop="success" :show-overflow-tooltip="true"
                v-if="columns.showColumn('success')">
                <template #default="{ row }">
                    <dict-tag :options="sys_result" :value="row.success" />
                </template>
            </el-table-column>
            <el-table-column label="耗时（ms）" align="center" prop="duration" :show-overflow-tooltip="true"
                v-if="columns.showColumn('duration')">
                <template #default="{ row }">
                    <el-text :type="row.duration <= 500 ? 'success'
                        : row.duration > 500 && row.duration <= 1000 ? 'warning'
                            : 'danger'">
                        {{ row.duration }}
                    </el-text>
                </template>
            </el-table-column>

            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button type="primary" text icon="delete" @click="handleDelete(scope.row)"
                        v-hasFunc="'job:log:del'">删除</el-button>
                    <el-button type="primary" text icon="view" @click="handleView(scope.row)"
                        v-hasFunc="'job:log:info'">查看</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageIndex"
            v-model:limit="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改对话框 -->
        <el-dialog :title="title" v-model="open" width="500px" draggable align-center destroy-on-close
            :close-on-click-modal="false">
            <el-form ref="formRef" :model="form" label-width="80px">
                <el-row :gutter="20">
                    <el-col :lg="24">
                        <el-form-item label="主键" prop="historyId">
                            <el-input v-model="form.historyId" placeholder="请输入主键" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="24">
                        <el-form-item label="作业标识" prop="jobId">
                            <el-input v-model="form.jobId" placeholder="请输入作业标识" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="24">
                        <el-form-item label="触发编码" prop="triggerId">
                            <el-input v-model="form.triggerId" placeholder="请输入触发编码" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="12">
                        <el-form-item label="执行时间" prop="startTime">
                            <el-date-picker v-model="form.startTime" type="datetime" placeholder="选择执行时间"
                                format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="12">
                        <el-form-item label="结束时间" prop="endTime">
                            <el-date-picker v-model="form.endTime" type="datetime" placeholder="选择结束时间"
                                format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="12">
                        <el-form-item label="耗时（ms）" prop="duration">
                            <el-text>{{ form.duration }}</el-text>
                        </el-form-item>
                    </el-col>
                    <el-col :lg="12">
                        <el-form-item label="作业结果" prop="success">
                            <dict-tag :options="sys_result" :value="form.success" />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="24">
                        <el-form-item label="执行编码" prop="fireInstanceId">
                            <el-input v-model="form.fireInstanceId" placeholder="请输入执行编码" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="24">
                        <el-form-item label="错误消息" prop="errorMessage">
                            <el-input v-model="form.errorMessage" resize="none" type="textarea" :rows="3" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="cancel">关闭</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { listJobExecutionHistory, getJobExecutionHistory, delJobExecutionHistory,clearAllJobExecutionHistory } from "@/api/schedule/jobexecutionhistory.js";

const { proxy } = getCurrentInstance()


//弹窗操作类型
//0:新增，1：修改，2:查看
const operateType = ref(0)
//表单ref
const formRef = ref();
// 遮罩层
const loading = ref(true);
// 选中数组
const selected = ref([]);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 数据集
const dataList = ref([]);
// 弹出层标题
const title = ref("");
// 是否显示弹出层
const open = ref(false);
const tableRef = ref();

//默认时间范围
const defaultTime = ref([new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)])

const dicts = ["sys_result"];
const dictRefs = proxy.useDict(...dicts);
const { sys_result } = dictRefs;

// 查询参数
const queryParams = reactive({
    pageIndex: 1,
    pageSize: 10,
    jobName: undefined,  // 新增作业名称查询
    success: undefined,   // 新增执行结果查询
    sort: 'StartTime'
});



const state = reactive({
    single: true,
    multiple: true,
    form: {

    }
})

const { form, single, multiple } = toRefs(state)


//所有列
const columns = ref([
    { visible: false, prop: 'historyId', label: '主键' },
    { visible: true, prop: 'jobName', label: '作业名' },
    { visible: false, prop: 'jobId', label: '作业标识' },
    { visible: true, prop: 'fireInstanceId', label: '执行编码' },
    { visible: false, prop: 'triggerId', label: '触发编码' },
    { visible: true, prop: 'startTime', label: '执行时间' },
    { visible: true, prop: 'endTime', label: '结束时间' },
    { visible: false, prop: 'createdAt', label: '创建时间' },
    { visible: true, prop: 'success', label: '作业结果' },
    { visible: true, prop: 'duration', label: '耗时（ms）' },
]);

// 获取列表方法
const getList = () => {
    loading.value = true;
    listJobExecutionHistory(queryParams).then((response) => {
        dataList.value = response.result;
        total.value = response.totalNum;
        loading.value = false;
    });
};

// 重置表单
const reset = () => {
    proxy.resetForm("queryForm");
};

// 搜索按钮操作
const handleQuery = () => {
    queryParams.pageIndex = 1;
    getList();
};

// 重置按钮操作
const resetQuery = () => {
    reset();
    handleQuery();
};

// 多选框选中数据
const handleSelectionChange = (selection) => {
    selected.value = selection.map((item) => item.historyId);
    single.value = selection.length !== 1;
    multiple.value = !selection.length;
};

// 新增按钮操作
const handleAdd = () => {
    reset();
    operateType.value = 0;
    open.value = true;
    title.value = "添加数据";
};



//查看
const handleView = (row) => {
    reset();
    operateType.value = 2;
    var key = row.historyId;
    getJobExecutionHistory(key).then((response) => {
        Object.assign(form.value, response);
        open.value = true;
        title.value = "查看明细";
    });
}

//取消弹窗
const cancel = () => {
    open.value = false;
    proxy.resetForm("form")
}

// 删除按钮操作
const handleDelete = (row) => {
    const keys = [].concat(row.historyId || selected.value);
    proxy.$modal.confirm("是否确认删除编号为" + keys + "的数据项？")
        .then(() => delJobExecutionHistory(keys))
        .then(() => {
            getList();
            proxy.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
};

//清空所有
const handleClearAll = () => {
    proxy.$modal.confirm("是否确认清空所有作业执行记录？")
        .then(() => clearAllJobExecutionHistory())
        .then(() => {
            getList();
            proxy.$modal.msgSuccess("清空成功");
        })
        .catch(() => { });
}


// 新增行点击处理
const handleRowClick = (row) => {
    tableRef.value.toggleRowSelection(row)
}

// 页面加载时调用获取列表方法
onMounted(getList);

</script>
